const app = getApp();


function unique(arr) {
  var result = [],
    hash = {};
  for (var i = 0, elem;
    (elem = arr[i]) != null; i++) {
    if (!hash[elem]) {
      result.push(elem);
      hash[elem] = true;
    }
  }
  return result;
}



// pages/setTopic/setTopic.js
Page({
  data: {
    clickSubmit: false,
    isAuthorize:false,
    eng: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'N', 'M'],
    server_url: '',
    next: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
    is_verify:1,
    imgUrl: 'https://wjf.wayoxi.com/images/imgUpload.png',
    mold: ['单选题', '多选题', '排序题', '地区', '逻辑'],
    type3: [],
    tips: 0,
    useArr: [],
    banner: '',
    moldIndex: 0,
    subject: {
      questionnaire_id: '',
      content: '',
      describe: '',
      banner: '',
      question: []
    }
  },

  inputTitle: function(e) {
    var title = "subject.title";
    if (this.data.clickSubmit && e.detail.value == '') {
      this.setData({
        [title]: true
      });
    };
    this.setData({
      [title]: e.detail.value
    });
  },

  search: function() {
    wx.navigateTo({
      url: 'search/search',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  inputDescript: function(e) {
    var describe = "subject.describe";
    this.setData({
      [describe]: e.detail.value
    });
  },

  addItem: function() {
    var that = this;
    var index = that.data.subject.question.length;

    if (this.data.subject.question.length >= 15) {
      this.setData({
        tips: this.data.tips + 1
      });

      setTimeout(function() {
        that.setData({
          tips: 0
        });
      }, 2000)

    } else {
      var question = "subject.question[" + this.data.subject.question.length + "]";
      this.setData({
        [question]: {
          id: 0,
          content: '',
          'type': 0,
          select_num:0,
          options: []
        }
      });
      this.setData({
        tips: 0
      });
    };

    that.addSubject(index);
    that.addSubject(index);
  },

  addSubject: function(e) {
    var that = this;
    var index = '';
    if (e.currentTarget) {
      index = e.currentTarget.dataset.index;
    } else {
      index = e;
    }

    var options = this.data.subject.question[index].options;
    this.setData({
      ["subject.question[" + index + "].options[" + options.length + "]"]: {
        id: 0,
        content: '',
        type: 1,
        next_question: 0
      }
    });
    
    that.countType3()

  },

  redItem: function(e) {
    var that = this;
    var newArr = this.data.subject.question;
    var useId = e.currentTarget.dataset.useid;

    if (newArr.length == 1) {
      wx.showToast({
        title: '问卷至少有一个问题！',
        icon: 'none',
        duration: 2000,
      });
      return
    } else {
      newArr.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        ['subject.question']: newArr
      });
      if (useId != undefined) {
        Array.prototype.remove = function(val) {
          var index = this.indexOf(val);
          if (index > -1) {
            this.splice(index, 1);
          }
        };
        var useArr = that.data.useArr
        useArr.remove(useId)
        that.setData({
          useArr: useArr
        })
      }

    };
    that.countType3()
  },

  redSubject: function(e) {
    var that =this;
    var index = e.currentTarget.dataset.index;
    var indexs = e.currentTarget.dataset.indexs;
    var newArr = this.data.subject.question[index].options;
    if (indexs <= 1) {
      wx.showToast({
        title: '题目至少包括两个答案!',
        icon: 'none',
        duration: 2000,
      });
      return
    } else {
      newArr.splice(indexs, 1);
      this.setData({
        ['subject.question[' + index + '].options']: newArr
      });
    };
    that.countType3()
  },

  imgSubject: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var indexs = e.currentTarget.dataset.indexs;

    wx.chooseImage({
      count: 1, // 默认9  
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function(res) {
        wx.showLoading({
          title: '图片上传中...',
        })
        wx.uploadFile({
          url: app.globalData.phpUrl + 'Publish/api',
          filePath: res.tempFilePaths[0],
          name: 'img',
          header: {
            "Content-Type": "multipart/form-data",
          },
          formData: {
            'api_name': 'upload',
            'type': 1,
          },
          success: function (ress) {
            wx.hideLoading();
            if (JSON.parse(ress.data).code == -1) {
              that.setData({
                ['subject.question[' + index + '].options[' + indexs + '].file_url']: '',
                ['subject.question[' + index + '].options[' + indexs + '].type']: 1,
              });
              wx.showToast({
                title: JSON.parse(ress.data).msg + '！',
                icon: 'none',
                duration: 2000,
              });
            };
            if (JSON.parse(ress.data).code == 1) {
              that.setData({
                ['subject.question[' + index + '].options[' + indexs + '].file_url']: JSON.parse(ress.data).data,
                ['subject.question[' + index + '].options[' + indexs + '].type']: 2,
              });
            }
          },
          fail: function (e) {
            wx.hideLoading();
            wx.showToast({
              title: '上传失败!',
              icon: 'none',
              duration: 2000,
            });
          }
        })
      }
    })

  },

  downSort: function(e) {

    Array.prototype.insert = function (index, item) {
      this.splice(index, 0, item);
    };
    var that = this;
    var index = e.currentTarget.dataset.index;
    var indexData = this.data.subject.question[index];
    var arr = this.data.subject.question;
    arr.splice(index, 1);
    arr.insert(index + 1, indexData);

    this.setData({
      ['subject.question']: arr
    });
    that.countType3()
  },

  upSort: function(e) {

    Array.prototype.insert = function (index, item) {
      this.splice(index, 0, item);
    };

    var that = this;
    var index = e.currentTarget.dataset.index;
    var indexData = this.data.subject.question[index];
    var arr = this.data.subject.question;
    if(index == 0){
      return
    }

    arr.splice(index, 1);
    arr.insert(index - 1, indexData);

    this.setData({
      ['subject.question']: arr
    });

    that.countType3()
  },

  inputContent: function(e) {
    var content = "subject.question[" + e.currentTarget.dataset.index + "].content";
    this.setData({
      [content]: e.detail.value
    });
  },

  inputTextarea: function(e) {
    var content = "subject.question[" + e.currentTarget.dataset.index + "].options[" + e.currentTarget.dataset.indexs + "].content";
    this.setData({
      [content]: e.detail.value
    });
  },

  selectMold: function(e) {
    var that = this;
    var moldType = "subject.question[" + e.currentTarget.dataset.index + "].type";
    this.setData({
      [moldType]: e.detail.value
    });

    if (e.detail.value == 3) {
      this.setData({
        ["subject.question[" + e.currentTarget.dataset.index + "].options"]: ''
      });
    } else {
      if (that.data.subject.question[e.currentTarget.dataset.index].options == '') {
        that.addSubject(0);
        that.addSubject(0);
      }
    };
  },

  type3:function(e){
    var that = this;
    var select_num = "subject.question[" + e.currentTarget.dataset.index + "].select_num";
    this.setData({
      [select_num]: e.detail.value
    });
  },

  selectNext: function(e) {
    var index = e.currentTarget.dataset.index;
    var indexs = e.currentTarget.dataset.indexs;

    var next = "subject.question[" + index + "].options[" + indexs + "].next_question";
    this.setData({
      [next]: this.data.next[e.detail.value]
    });
  },

  choseImg: function (event) {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9  
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function(res) {
        wx.navigateTo({
          url: './cutImg/cutImg?url=' + res.tempFilePaths[0],
        })
      }
    })
  },

  choseImg2: function (event) {
    var that = this;
    if (event.detail.rawData) {
      app.globalData.userInfo = JSON.parse(event.detail.rawData);
      wx.chooseImage({
        count: 1, // 默认9  
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
        success: function (res) {
          // wx.navigateTo({
          //   url: './cutImg/cutImg?url=' + that.wecropper.pushOrign(res.tempFilePaths[0])
          // })
        }
      })
      wx.request({
        url: app.globalData.phpUrl + 'index/getUnionId',
        method: "POST",
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: { openid: app.globalData.userData.openOId, encrypteddata: event.detail.encryptedData, iv: event.detail.iv },
        success: function (e) {
        }
      })
      that.setData({
        isAuthorize: true
      });
    } else {
      that.setData({
        isAuthorize: false
      });
    }
  },

  finishNxt: function() {
    var that = this;
    wx.navigateTo({
      url: './setting/setting',
      success: function() {},
      fail: function() {},
      complete: function() {}
    })
  },

  clearLogo: function(e) {
    var that = this;
    that.setData({
      ['subject.question[' + e.target.dataset.index + '].options[' + e.target.dataset.indexs + '].file_url']: '',
      ['subject.question[' + e.target.dataset.index + '].options[' + e.target.dataset.indexs + '].type']: 1,
    })
  },

  formSubmit: function(e) {

    var that = this;
    
    var tpe = e.detail.target.dataset.type;
    var isFull = false;
    var valueData = e.detail.value;

    var question = that.data.subject.question;
    var oldType = [];
    for (var pp = 0; pp < question.length; pp++) {
      oldType[pp] = Number(question[pp].type);
      question[pp].type = Number(question[pp].type) + 1
    };

    that.setData({
      oldType: oldType
    });

    for (var n in valueData) {
      if (valueData[n] == '') {
        isFull = false;
        that.setData({
          clickSubmit: true
        })
        wx.showToast({
          title: '请填写完整问卷！',
          icon: 'none',
          duration: 2000,
        });
        for (var pp = 0; pp < question.length; pp++) {
          question[pp].type = oldType[pp]
        };
        break
      } else {
        isFull = true;
      }
    };

    var xinType = [];

    if (isFull) {
      if (question.length == 0) {
        wx.showToast({
          title: '问卷至少添加一个问题！',
          icon: 'none',
          duration: 2000,
        });

        for (var pp = 0; pp < question.length; pp++) {
          question[pp].type = oldType[pp]
        };
      } else {
        if (question[question.length - 1].type != 5) {
          if (tpe == 1) {
            wx.navigateTo({
              url: '../../../../preview/reply?source=' + 1,
            });
            return
          };
          var opid = app.globalData.userData.openOId;
          console.log('--提交问卷--');
          wx.showLoading({
            title: '上传中',
          });

          var sendData = {
            api_name: 'create',
            openid: opid,
            used_naires: unique(that.data.useArr),
            questionnaire_id: that.data.questionnaire_id,
            title: valueData['title'],
            cover: valueData['cover'],
            describe: valueData['describe'],
            questions: question,
          };

          sendQues(sendData);

          //发送全部表单
          function sendQues(d) {
            console.log('发送表单!')
            console.log(d)
            wx.request({
              url: app.globalData.phpUrl + 'Publish/api',
              method: "POST",
              header: {
                'content-type': 'application/json'
              },
              data: d,
              success: function(data) {
                wx.hideLoading();
                if (that.data.is_verify == 2){
                  wx.navigateTo({
                    url: './reviewItem/reviewItem?id=' + that.data.questionnaire_id + "&title=" + that.data.subject.title + "&cover=" + that.data.subject.banner,
                  });
                }else{
                  wx.navigateTo({
                    url: './setting/setting?id=' + data.data.data.questionnaire_id + '&cover=' + d.cover + '&title=' + d.title + '&question_count=' + d.questions.length
                  })
                }
              },
              fail: function(e) {
                console.log(e)
              }
            })
          };
        } else {
          for (var pp = 0; pp < question.length; pp++) {
            question[pp].type = oldType[pp]
          };
          wx.showToast({
            title: '最后一题不能为逻辑题！',
            icon: 'none',
            duration: 2000,
          });
        }
      }
    }
    //表单提交
  },

  onLoad: function (option) {
    if(option.id){
      app.globalData.setId = option.id
    }else{
      this.addItem(0);
    }
  },

  onHide: function() {
    app.globalData.setId = undefined
  },

  onShow: function () {    
    var that = this;
    if (app.globalData.userInfo) {
      that.setData({
        isAuthorize: true
      });
    } else {
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo;
          that.setData({ userInfo: res.userInfo });
          that.setData({
            isAuthorize: true
          })
        },
        fail: res => {
          isAuthorize: false
        }
      })
    };

    if (app.globalData.userData.openOId){
      if (app.globalData.setId) {
        var id = app.globalData.setId;
        wx.showLoading({
          title: '加载问卷中...',
        });

        wx.request({
          url: app.globalData.phpUrl + 'user/api',
          method: 'POST',
          data: {
            api_name: 'naire_detail',
            openid: app.globalData.userData.openOId,
            questionnaire_id: id
          },
          success: function (d) {
            console.log('gs');
            console.log(d)
            var qd = d.data.data;
            for (var o = 0; o < qd.question_data.length; o++) {
              qd.question_data[o].selected = false;
              qd.question_data[o].type = Number(qd.question_data[o].type) - 1;
              qd.question_data[o].id = 0;
              for (var uu = 0; uu < qd.question_data[o].options.length; uu++) {
                delete qd.question_data[o].options[uu].pid;
                qd.question_data[o].options[uu].id = 0;
                delete qd.question_data[o].options[uu].option_select;
                delete qd.question_data[o].options[uu].headimg_arr;
              }
            };

            that.setData({
              questionnaire_id: qd.questionnaire_id,
              is_verify: qd.is_verify,
              ['subject.banner']: qd.cover,
              ['subject.title']: qd.title,
              ['subject.describe']: qd.describe,
              banner: qd.cover,
              ['subject.question']: qd.question_data,
              ['subject.questionnaire_id']: qd.is_publish == 1 ? '' : qd.questionnaire_id
            });
            wx.hideLoading();
            that.countType3();
          }
        });

      } else {
        if (that.data.oldType) {
          var questionLength = that.data.subject.question.length;
          for (var pp = 0; pp < questionLength; pp++) {
            that.data.subject.question[pp].type = that.data.oldType[pp]
          }
        }
      }
    }else{
      wx.showLoading({
        title: '加载问卷中...',
      });
      app.globalData.loadQuestion = function (opId) {
        var id = app.globalData.setId
        wx.request({
          url: app.globalData.phpUrl + 'user/api',
          method: 'POST',
          data: {
            api_name: 'naire_detail',
            openid: app.globalData.userData.openOId,
            questionnaire_id: id
          },
          success: function (d) {
            var qd = d.data.data;
            for (var o = 0; o < qd.question_data.length; o++) {
              qd.question_data[o].selected = false;
              qd.question_data[o].type = Number(qd.question_data[o].type) - 1;
              qd.question_data[o].id = 0;
              for (var uu = 0; uu < qd.question_data[o].options.length; uu++) {
                delete qd.question_data[o].options[uu].pid;
                qd.question_data[o].options[uu].id = 0;
                delete qd.question_data[o].options[uu].option_select;
                delete qd.question_data[o].options[uu].headimg_arr;
              }
            };

            that.setData({
              questionnaire_id: qd.questionnaire_id,
              is_verify: qd.is_verify,
              ['subject.banner']: qd.cover,
              ['subject.title']: qd.title,
              ['subject.describe']: qd.describe,
              banner: qd.cover,
              ['subject.question']: qd.question_data,
              ['subject.questionnaire_id']: qd.is_publish == 1 ? '' : qd.questionnaire_id
            });
            wx.hideLoading();
            that.countType3();
          }
        });
      }
    }

    that.countType3();
  },

  countType3: function () {
    var that = this;
    var type3 = [];
    for (var uu = 0; uu < that.data.subject.question.length; uu++) {
      type3[uu] = [];
      type3[uu][0] = '不定选选';
      for (var oo = 1; oo < that.data.subject.question[uu].options.length + 1; oo++) {
        type3[uu][oo] = oo
      }
    };
    that.setData({
      type3: type3
    });
  }
})